package com.brush.web.controller.login;

import com.brush.common.constant.Constants;
import com.brush.common.core.controller.BaseController;
import com.brush.common.core.domain.R;
import com.brush.common.core.domain.entity.SysMenu;
import com.brush.common.core.domain.entity.SysRole;
import com.brush.common.core.domain.req.AdminLoginReq;
import com.brush.common.core.domain.resp.AdminUserDetails;
import com.brush.common.core.domain.resp.SysRoleResp;
import com.brush.common.utils.SecurityUtils;
import com.brush.framework.web.service.AdminLoginService;
import com.brush.system.domain.vo.RouterVo;
import com.brush.system.service.SysMenuService;
import com.brush.system.service.SysRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "后台-登录管理")
@RestController
@RequestMapping("/admin")
public class AdminLoginController extends BaseController {


    @Autowired
    private AdminLoginService adminLoginService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysMenuService sysMenuService;



    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public R<String> login(@Valid @RequestBody AdminLoginReq req){
        String token=this.adminLoginService.login(req);
        return R.ok(token);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @ApiOperation(value = "获取用户信息")
    @GetMapping("getInfo")
    public R<Map<String,Object>> getInfo()  {
        // 获取用户信息
        AdminUserDetails loginUser = SecurityUtils.getLoginUser();

        //---------------------优化代码，为了满足用户权限更新，在不用重新登录情况下，获取最新的数据-----------------
        // 获取最新的角色集合
        List<SysRole> sysRoleList =this.sysRoleService.findRoleByUserId(loginUser.getUserId());

        //获取最新角色的集合key
        Set<String> roles=sysRoleList.stream().map(SysRole::getRoleKey).collect(Collectors.toSet());

        Set<String> permissions=new HashSet<>();
        if(roles.contains(Constants.SUPER_ADMIN)){
            permissions.add(Constants.ALL_PERMISSION);
        }else{
            Set<Long> roleIdSet=sysRoleList.stream().map(SysRole::getRoleId).collect(Collectors.toSet());
            // 权限集合
            if(!roleIdSet.isEmpty()) {
                permissions = this.sysMenuService.findPermissionsByRoleIds(roleIdSet);
            }
        }

        // 赋值值，不要让前端用户，产生疑惑
        loginUser.setPermissions(permissions);

        List<SysRoleResp> sysRoleListResp= sysRoleList.stream().map(SysRoleResp::new).collect(Collectors.toList());

        loginUser.getUser().setRoles(sysRoleListResp);

        //---------------------上面优化代码，为了满足用户权限更新，在不用重新登录情况下，获取最新的数据-----------------

        Map<String,Object> ajax=new HashMap<>();
        ajax.put("user", loginUser);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);

        return R.ok(ajax);
    }


    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @ApiOperation(value = "获取路由信息")
    @GetMapping("getRouters")
    public R<List<RouterVo>> getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        // 查询用户拥有的菜单
        List<SysMenu> menus = sysMenuService.selectMenuTreeByUserId(userId);
        //把菜单，构造成前端需要的json格式

        /*
        {
            path: '',
            component: Layout,
            redirect: 'index',
            // 二级路由
            children: [
              {
                path: 'index',
                component: () => import('@/views/index'),
                name: 'Index',
                meta: { title: '首页', icon: 'dashboard', affix: true }
              }
            ]
          }
         */
        List<RouterVo> routerVos=this.sysMenuService.buildMenus(menus);
        return R.ok(routerVos);
    }

}
